package com.cardone.platform.authority.controller;

import java.util.List;
import java.util.Map;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cardone.common.dto.PaginationDto;
import com.cardone.context.Constants;
import com.cardone.platform.authority.dto.NavigationDto;
import com.cardone.platform.authority.service.AuthorityService;
import com.cardone.platform.authority.validator.NavigationValidator;
import com.cardone.platform.authority.vo.NavigationVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 导航
 * 
 * @author yaoht
 */
@Setter
@Slf4j
@RequestMapping(NavigationController.Paths.ROOT)
@Controller
public class NavigationController {
	/**
	 * models集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum models {
		/**
		 * 消息
		 */
		message,

		/**
		 * 导航
		 */
		navigation;
	}

	/**
	 * 路径集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum Paths {
		/**
		 * 导航主界面
		 */
		index,

		/**
		 * 导航编辑视图路径
		 */
		NAVIGATIONEdit("navigation/edit"),

		/**
		 * 导航主界面视图路径
		 */
		NAVIGATIONIndex("navigation/index"),

		/**
		 * 导航编辑视图路径
		 */
		NAVIGATIONNew("navigation/new"),

		/**
		 * 导航查看编辑视图路径
		 */
		NAVIGATIONView("navigation/view");

		/**
		 * 导航视图根目录
		 */
		public static final String ROOT = "/platform/authority/navigation/";

		/**
		 * 路径
		 */
		private final String path;

		/**
		 * 构建
		 * 
		 */
		private Paths() {
			this.path = Paths.ROOT + this.name();
		}

		/**
		 * 构建
		 * 
		 * @param path
		 *            路径
		 */
		private Paths(final String path) {
			this.path = Paths.ROOT + path;
		}

		/**
		 * 获取
		 * 
		 * @return 路径
		 */
		public String path() {
			return this.path;
		}
	}

	/**
	 * 导航服务
	 */
	@Qualifier(AuthorityService.BEAN_ID)
	@Autowired(required = false)
	private AuthorityService authorityService;

	/**
	 * 导航验证
	 */
	@Qualifier(NavigationValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator navigationValidator;

	/**
	 * 导航：删除
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "navigation/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> navigationDelete(final NavigationVo navigationVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getNavigationService().deleteNavigationByIds(navigationVo.getNavigation());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (NavigationController.log.isDebugEnabled()) {
				NavigationController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 导航：编辑
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @param model
	 *            上下文映射
	 * @return 导航编辑视图路径
	 */
	@RequestMapping(value = { "navigation/edit.html" }, method = RequestMethod.GET)
	public String navigationEdit(final NavigationVo navigationVo, final Model model) {
		final NavigationDto navigation = this.authorityService.getNavigationService().findNavigationById(navigationVo.getNavigation());

		model.addAttribute(NavigationController.models.navigation.name(), navigation);

		return NavigationController.Paths.NAVIGATIONEdit.path();
	}

	/**
	 * 导航：主界面
	 * 
	 * @return 导航主界面视图路径
	 */
	@RequestMapping(value = { "navigation/index.html" })
	public String navigationIndex() {
		return NavigationController.Paths.NAVIGATIONIndex.path();
	}

	/**
	 * 导航：主界面分页查询
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "navigation/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> navigationIndexPagination(final NavigationVo navigationVo) {
		final PaginationDto<NavigationDto> navigationPagination = this.authorityService.getNavigationService()
		        .paginationNavigationByCode(navigationVo.getNavigation());

		final Map<String, Object> navigationPaginationMap = Maps.newHashMap();

		navigationPaginationMap.put(Constants.total.stringValue(), navigationPagination.getTotalSize());
		navigationPaginationMap.put(Constants.rows.stringValue(), navigationPagination.getDataList());

		return navigationPaginationMap;
	}

	/**
	 * 导航：新增
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @param model
	 *            上下文映射
	 * @return 导航编辑视图路径
	 */
	@RequestMapping(value = { "navigation/new.html" }, method = RequestMethod.GET)
	public String navigationNew(final NavigationVo navigationVo, final Model model) {
		model.addAttribute(NavigationController.models.navigation.name(), navigationVo.getNavigation());

		return NavigationController.Paths.NAVIGATIONNew.path();
	}

	/**
	 * 导航：保存
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "navigation/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String navigationSave(final NavigationVo navigationVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.navigationValidator.validate(navigationVo.getNavigation(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.authorityService.getNavigationService().saveNavigationByIdOrCode(navigationVo.getNavigation());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (NavigationController.log.isDebugEnabled()) {
				NavigationController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 导航：更新
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "navigation/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> navigationUpdate(final NavigationVo navigationVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getNavigationService().updateNavigationByIds(navigationVo.getNavigation());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (NavigationController.log.isDebugEnabled()) {
				NavigationController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 导航：验证
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "navigation/validationByCode.json" })
	@ResponseBody
	public Boolean navigationValidationByCode(final NavigationVo navigationVo) {
		try {
			final int count = this.authorityService.getNavigationService().readNavigationByCodeNqId(navigationVo.getNavigation());

			return (count < 1);
		} catch (final Exception e) {
			if (NavigationController.log.isDebugEnabled()) {
				NavigationController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 导航：查看
	 * 
	 * @param navigationVo
	 *            导航视图对象
	 * @param model
	 *            上下文映射
	 * @return 导航查看编辑视图路径
	 */
	@RequestMapping(value = { "navigation/view.html" }, method = RequestMethod.GET)
	public String navigationView(final NavigationVo navigationVo, final Model model) {
		final NavigationDto navigation = this.authorityService.getNavigationService().findNavigationById(navigationVo.getNavigation());

		model.addAttribute(NavigationController.models.navigation.name(), navigation);

		return NavigationController.Paths.NAVIGATIONView.path();
	}
}
